package com.shupian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shupian.constants.SystemConstants;
import com.shupian.domain.ResponseResult;
import com.shupian.domain.dto.AddArticleDto;
import com.shupian.domain.entity.Article;
import com.shupian.domain.entity.ArticleTag;
import com.shupian.domain.entity.Category;
import com.shupian.domain.vo.*;
import com.shupian.enums.AppHttpCodeEnum;
import com.shupian.mapper.ArticleMapper;
import com.shupian.mapper.ArticleTagMapper;
import com.shupian.service.ArticleService;
import com.shupian.service.ArticleTagService;
import com.shupian.service.CategoryService;
import com.shupian.utils.BeanCopyUtils;
import com.shupian.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章，分装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //浏览量前10
        queryWrapper.orderByDesc(Article::getViewCount);
        Page<Article> page = new Page(1,10);
        page(page,queryWrapper);
        List<Article> articles = page.getRecords();
        //bean拷贝
        //List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        //for (Article article: articles) {
        //    HotArticleVo hotArticleVo = new HotArticleVo();
        //    BeanUtils.copyProperties(article,hotArticleVo);
        //    hotArticleVoList.add(hotArticleVo);
        //}
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);


        return ResponseResult.okResult(hotArticleVos);
    }

    /**
     * 在首页和分类页面都需要查询文章列表。
     * 首页：查询所有的文章
     * 分类页面：查询对应分类下的文章
     * 	要求：①只能查询正式发布的文章 ②置顶的文章要显示在最前面
     *
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @param categoryId 分类id
     * @return
     */
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询添加
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //如果有categoryId 就要 查询时要和传入的相同
        lambdaQueryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,Article::getCategoryId,categoryId);
        //状态是正式发布的
        lambdaQueryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //对isTop进行降序
        lambdaQueryWrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,lambdaQueryWrapper);
        //查询categoryName
        List<Article> articles = page.getRecords();

        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());
        //categoryService.getById()
        //分装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);


        PageVo pageVo = new PageVo(articleListVos,page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue(SystemConstants.ARTICLE_VIEWCOUNT_KEY, id.toString());
        article.setViewCount(Long.valueOf(viewCount));
        //转化成vo
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category!=null){
            articleDetailVo.setCategoryName(category.getName());
        }
        //分装返回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应的存在 id 的浏览量
        redisCache.incrementCacheMapValue(SystemConstants.ARTICLE_VIEWCOUNT_KEY,id.toString(),1);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult addArticle(AddArticleDto addArticleDto) {
        //处理文章信息传入数据库
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        Long categoryId = addArticleDto.getCategoryId();
        //将浏览量设置为0
        article.setViewCount(0L);
        save(article);
        //处理标签信息
        Long id = article.getId();
        List<Long> tags = addArticleDto.getTags();

        for (Long tag: tags) {
            articleTagService.save(new ArticleTag(id,tag));
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getList(Integer pageNum, Integer pageSize, String title, String summary) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isBlank(title),Article::getTitle,title);
        queryWrapper.like(!StringUtils.isBlank(summary),Article::getSummary,summary);
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);
        List<Article> articleList = page.getRecords();
        List<ArticleAdminListVo> articleAdminListVos = BeanCopyUtils.copyBeanList(articleList, ArticleAdminListVo.class);
        PageVo pageVo = new PageVo(articleAdminListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleById(Integer id) {
        Article article = getById(id);
        ArticleInfoVo articleInfoVo = BeanCopyUtils.copyBean(article, ArticleInfoVo.class);
        List<Integer> tagId = articleTagMapper.getTagId(id);
        articleInfoVo.setTags(tagId);

        return ResponseResult.okResult(articleInfoVo);
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        if (removeById(id)){
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);

    }
}
